<script setup lang="ts">
import { ref, onMounted, h, computed } from 'vue'
import {
  Card,
  Table,
  Form,
  Input,
  Button,
  Space,
  DatePicker,
  message,
  Modal,
  Tag,
  Progress,
  Tooltip,
  Popconfirm,
  Tree,
  Spin,
  Select
} from 'ant-design-vue'
import { SearchOutlined, ReloadOutlined, PlusOutlined, EditOutlined, DeleteOutlined, DownloadOutlined } from '@ant-design/icons-vue'
import type { TableColumnType } from 'ant-design-vue'
import type { TaskVO, TaskDTO } from '@/types/task'
import { taskApi } from '@/api/modules/task'
import { teacherClassApi } from '@/api/modules/teacherClass'
import type { ClassTreeVO } from '@/types/organization'
import locale from 'ant-design-vue/es/date-picker/locale/zh_CN';
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn';
dayjs.locale('zh-cn');
import SubmissionList from './components/SubmissionList.vue'
import { useRouter } from 'vue-router'

// 搜索表单类型
interface SearchForm {
  name: string
  classIds: number[]
  timeRange: null | [dayjs.Dayjs, dayjs.Dayjs]
  taskStatus?: 'IN_PROGRESS' | 'ENDED'
  sort?: string
}

// 加载状态
const loading = ref(false)
// 状态选项
const statusOptions = [
  { label: '进行中', value: 'IN_PROGRESS' },
  { label: '已结束', value: 'ENDED' }
]
// 表格数据
const tableData = ref<TaskVO[]>([])
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: (total: number) => `共 ${total} 条记录`,
  showSizeChanger: true,
  pageSizeOptions: ['10', '20', '30', '50'],
  // 自定义页码选项的文本
  buildOptionText: (opt: { value: number }) => {
    return `${opt.value} 条/页`
  }
})

// 搜索表单
const searchForm = ref<SearchForm>({
  name: '',
  classIds: [],
  timeRange: null,
  // 状态， 进行中，已结束
  taskStatus: undefined,
  sort: undefined
})

// 表单相关
const modalVisible = ref(false)
const modalTitle = ref('')
const modalLoading = ref(false)
const formRef = ref()

// 表单数据
const formState = ref<TaskDTO>({
  name: '',
  description: '',
  deadline: '',
  fileRequirements: '',
  submitRequirements: '',
  classIds: []
})

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入任务名称', trigger: 'blur' },
    { max: 50, message: '任务名称最多50个字符', trigger: 'blur' }
  ],
  deadline: [
    { required: true, message: '请选择截止时间', trigger: 'change' },
  ]
}

// 表格列配置
const columns: TableColumnType<TaskVO>[] = [
  {
    title: '任务名称',
    align: 'center',
    dataIndex: 'name',
    width: 200
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 100,
    align: 'center',
    customRender: ({ record }) => {
      const isExpired = dayjs(record.deadline).isBefore(dayjs())
      return h(Tag, {
        color: isExpired ? 'error' : 'success'
      }, () => isExpired ? '已结束' : '进行中')
    }
  },
  {
    title: '截止时间',
    align: 'center',
    dataIndex: 'deadline',
    width: 180,

    customRender: ({ text }) => dayjs(text).format('YYYY-MM-DD HH:mm:ss')
  },
  {
    title: '班级',
    align: 'center',
    dataIndex: 'classInfo',
    width: 300,
    customRender: ({ record }) => {
      return record.classInfo.collegeName+' / '+record.classInfo.majorName+' / '+record.classInfo.name
    }
  },
  {
    title: '文件要求',
    dataIndex: 'fileRequirements',
    width: 200,
    align: 'center',
    customRender: ({ text }) => {
      if (!text) return '-'
      return h(Tooltip, {
        title: text,
        placement: 'topLeft'
      }, () => text.length > 20 ? `${text.slice(0, 20)}...` : text)
    }
  },
  {
    title: '提交要求',
    dataIndex: 'submitRequirements',
    width: 200,
    align: 'center',
    customRender: ({ text }) => {
      if (!text) return '-'
      return h(Tooltip, {
        title: text,
        placement: 'topLeft'
      }, () => text.length > 20 ? `${text.slice(0, 20)}...` : text)
    }
  },
  {
    title: '提交情况',
    dataIndex: 'statistics',
    width: 200,
    align: 'center',

    customRender: ({ record }) => {
      const percent = Number(record.statistics.submissionRate.replace('%', ''))
      return h('div', { 
        class: 'submission-progress',
        style: {
          display: 'flex',
          alignItems: 'center',
          gap: '8px',
          justifyContent: 'center',
          cursor: 'pointer'
        },
        onClick: () => handleViewSubmissions(record)
      }, [
        h(Progress, {
          type: 'circle',
          size: 'small', 
          percent: percent,
          status: percent === 100 ? 'success' : percent < 60 ? 'exception' : 'active'
        }),
        h('div', { 
          class: 'progress-detail',
          style: {
            display: 'flex',
            flexDirection: 'column',
            justifyContent: 'center'
          }
        }, [
          h('span', { class: 'count' }, `${record.statistics.submittedCount}/${record.statistics.totalCount}`)
        ])
      ])
    }
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 180,
    align: 'center',
    customRender: ({ text }) => dayjs(text).format('YYYY-MM-DD HH:mm')
  },
  {
    title: '操作',
    key: 'action',
    width: 280,
    fixed: 'right',
    align: 'center',
    customRender: ({ record }) => {
      return h(Space, {}, [
        h(Button, {
          type: 'link',
          onClick: () => handleEdit(record)
        }, () => [
          h(EditOutlined),
          '编辑'
        ]),
        h(Button, {
          type: 'link',
          onClick: () => handleExportUnsubmitted(record)
        }, () => [
          h(DownloadOutlined),
          '导出未交名单'
        ]),
        h(Button, {
          type: 'link',
          onClick: () => handleExportSubmitted(record)
        }, () => [
          h(DownloadOutlined),
          '导出文件列表'
        ]),
        h(Popconfirm, {
          title: '确定要删除该任务吗？',
          okText: '确认',
          cancelText: '取消',
          onConfirm: () => handleDelete(record.id)
        }, {
          default: () => h(Button, {
            type: 'link',
            danger: true
          }, () => [
            h(DeleteOutlined),
            '删除'
          ])
        })
      ])
    }
  }
]

// 树形结构相关
const treeData = ref<ClassTreeVO[]>([])
const selectedKeys = ref<number[]>([])
const treeLoading = ref(false)

// 获取所有班级 ID
const getAllClassIds = (data: ClassTreeVO[]): number[] => {
  const ids: number[] = []
  const traverse = (items: ClassTreeVO[]) => {
    items.forEach(item => {
      if (item.type === 3) { // 假设 3 是班级类型
        ids.push(item.id)
      }
      if (item.children?.length) {
        traverse(item.children)
      }
    })
  }
  traverse(data)
  return ids
}

// 获取班级树
const fetchClassTree = async () => {
  loading.value = true
  try {
    const data = await teacherClassApi.getClassTree()
    treeData.value = data || []
    // 初始化时获取所有班级的任务
    fetchTaskList()
  } catch (error) {
    console.error('获取班级树失败:', error)
    message.error(error||'获取班级树失败')
  } finally {
    loading.value = false
  }
}

// 处理树节点选择
const handleSelect = (keys: number[]) => {
  selectedKeys.value = keys
  // 更新搜索条件并重新加载数据
  searchForm.value.classIds = keys
  // 重置分页
  pagination.value.current = 1
  fetchTaskList()
}

// 转换树形数据
const treeNodes = computed(() => {
  const convert = (items: ClassTreeVO[]): any[] => {
    if (!items?.length) return []
    return items.map(item => ({
      key: item.id,
      title: item.name,
      children: item.children ? convert(item.children) : undefined,
      selectable: item.type === 3 // 只有班级节点可选
    }))
  }
  return convert(treeData.value)
})

// 获取任务列表
const fetchTaskList = async () => {
  loading.value = true
  try {
    const data = await taskApi.getTaskPage({
      name: searchForm.value.name,
      // 如果没有选中班级，则使用所有班级的 ID
      classIds: selectedKeys.value.length ? selectedKeys.value : getAllClassIds(treeData.value),
      startTime: searchForm.value.timeRange?.[0]?.format('YYYY-MM-DD HH:mm:ss'),
      endTime: searchForm.value.timeRange?.[1]?.format('YYYY-MM-DD HH:mm:ss'),
      taskStatus: searchForm.value.taskStatus,
      page: pagination.value.current - 1,
      size: pagination.value.pageSize,
      sort: searchForm.value.sort
    })
    
    tableData.value = data.content
    pagination.value = {
      ...pagination.value,
      total: data.totalElements
    }
  } catch (error) {
    console.error('获取任务列表失败:', error)
    message.error(error||'获取任务列表失败')
  } finally {
    loading.value = false
  }
}

// 处理表格变化
const handleTableChange = (pag: any, filters: any, sorter: any) => {
  pagination.value.current = pag.current
  pagination.value.pageSize = pag.pageSize
  fetchTaskList()
}

// 处理搜索
const handleSearch = () => {
  pagination.value.current = 1
  fetchTaskList()
}

// 重置搜索
const handleReset = () => {
  searchForm.value = {
    name: '',
    classIds: selectedKeys.value, // 保留选中的班级
    timeRange: null,
    sort: undefined
  }
  pagination.value.current = 1
  fetchTaskList()
}

// 新增任务
const handleAdd = () => {
  formState.value = {
    name: '',
    description: '',
    deadline: '',
    fileRequirements: '',
    submitRequirements: '',
    classId: [...selectedKeys.value][0]
  }
  modalTitle.value = '新增任务'
  modalVisible.value = true
}

// 编辑任务
const handleEdit = (record: TaskVO) => {
  formState.value = {
    id: record.id,
    name: record.name,
    description: record.description || '',
    deadline: dayjs(record.deadline),
    fileRequirements: record.fileRequirements || '',
    submitRequirements: record.submitRequirements || '',
    classId: record.classInfo.id
  }
  modalTitle.value = '编辑任务'
  modalVisible.value = true
}

// 删除任务
const handleDelete = async (id: number) => {
  try {
    await taskApi.delete(id)
    message.success('删除成功')
    fetchTaskList()
  } catch (error) {
    console.error('删除失败:', error)
    message.error(error||'删除失败')
  }
}

// 处理提交
const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    modalLoading.value = true
    
    const data = {
      ...formState.value,
      deadline: dayjs(formState.value.deadline).format('YYYY-MM-DD HH:mm:ss'),
      classId: formState.value.id ? formState.value.classId : [...selectedKeys.value][0]
    }
    
    if (formState.value.id) {
      await taskApi.update(formState.value.id, data)
      message.success('更新成功')
    } else {
      await taskApi.create(data)
      message.success('创建成功')
    }
    
    modalVisible.value = false
    fetchTaskList()
  } catch (error) {
    console.error('提交失败:', error)
    message.error(error||'提交失败')
  } finally {
    modalLoading.value = false
  }
}

// 获取选中班级的名称
const getSelectedClassNames = computed(() => {
  const findClassName = (nodes: ClassTreeVO[], id: number): string | undefined => {
    for (const node of nodes) {
      if (node.id === id) return node.name
      if (node.children?.length) {
        const found = findClassName(node.children, id)
        if (found) return found
      }
    }
    return undefined
  }
  
  return selectedKeys.value
    .map(id => findClassName(treeData.value, id))
    .filter(Boolean)
    .join('、')
})


// 查看提交列表
const handleViewSubmissions = (record: TaskVO) => {
  router.push(`/teacher/task/submission/${record.id}`)
}

// 处理导出未提交学生名单
const handleExportUnsubmitted = async (record: TaskVO) => {
  try {
    const blob = await teacherClassApi.exportUnsubmittedStudents(record.id)
    const fileName = `${record.name}-未提交学生名单.xlsx`
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = fileName
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    message.success('导出成功')
  } catch (error: any) {
    console.error('导出失败:', error)
    message.error(error.message || '导出失败')
  }
}

// 处理导出已提交文件列表
const handleExportSubmitted = async (record: TaskVO) => {
  try {
    const response = await fetch(`/api/v1/tasks/${record.id}/submissions/files/export`, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${localStorage.getItem('token')}`
      }
    })
    
    if (!response.ok) {
      throw new Error('导出失败')
    }

    const blob = await response.blob()
    const fileName = `${record.name}-提交文件.zip`
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = fileName
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    window.URL.revokeObjectURL(url)
    message.success('导出成功')
  } catch (error: any) {
    console.error('导出失败:', error)
    message.error(error.message || '导出失败')
  }
}

const router = useRouter()

onMounted(() => {
  fetchClassTree() // 不再直接调用 fetchTaskList，而是在获取班级树后调用
})
</script>

<template>
  <div class="task-page">
    <div class="page-container">
      <!-- 左侧班级树 -->
      <Card class="tree-card" title="班级列表">
        <Spin :spinning="treeLoading">
          <Tree
            v-model:selectedKeys="selectedKeys"
            :tree-data="treeNodes"
            :default-expand-all="true"
            @select="handleSelect"
          />
        </Spin>
      </Card>

      <!-- 右侧内容区 -->
      <Card class="content-card">
        <!-- 搜索区域 -->
        <div class="table-search">
          <div class="search-left">
            <Space>
              <Input
                v-model:value="searchForm.name"
                placeholder="请输入任务名称"
                style="width: 200px"
                allowClear
              />
              <DatePicker.RangePicker
                v-model:value="searchForm.timeRange"
                style="width: 300px"
                :locale="locale"
                :placeholder="['开始时间', '结束时间']"
              />
                <Select
                    v-model:value="searchForm.taskStatus"
                    placeholder="请选择状态"
                    style="width: 150px"
                    allowClear
                >
                  <Select.Option v-for="option in statusOptions"
                                 :key="option.value"
                                 :value="option.value"
                  >
                    {{ option.label }}
                  </Select.Option>
                </Select>
              <Button type="primary" @click="handleSearch">
                <template #icon><SearchOutlined /></template>
                查询
              </Button>
              <Button @click="handleReset">
                <template #icon><ReloadOutlined /></template>
                重置
              </Button>
            </Space>
          </div>
          <div class="search-right">
            <Button 
              type="primary" 
              :disabled="!selectedKeys.length"
              @click="handleAdd"
            >
              <template #icon><PlusOutlined /></template>
              新增任务
            </Button>
          </div>
        </div>

        <Table
          :columns="columns"
          :data-source="tableData"
          :loading="loading"
          :pagination="pagination"
          @change="handleTableChange"
        />
      </Card>
    </div>

    <!-- 新增/编辑弹窗 -->
    <Modal
      :title="modalTitle"
      :maskClosable="false"
      :open="modalVisible"
      :confirm-loading="modalLoading"
      @ok="handleSubmit"
      @cancel="modalVisible = false"
      width="700px"
      okText="确认"
      cancelText="取消"
    >
      <Form
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 19 }"
      >
        <Form.Item label="任务名称" name="name">
          <Input v-model:value="formState.name" placeholder="请输入任务名称" />
        </Form.Item>

        <Form.Item label="截止时间" name="deadline">
          <DatePicker
            v-model:value="formState.deadline"
            show-time
            :locale="locale"
            style="width: 100%"
            placeholder="请选择截止时间"
          />
        </Form.Item>

        <Form.Item 
          v-if="!formState.id" 
          label="班级"
        >
          <span>{{ getSelectedClassNames }}</span>
        </Form.Item>

        <Form.Item label="任务描述" name="description">
          <Input.TextArea
            v-model:value="formState.description"
            placeholder="请输入任务描述"
            :rows="4"
          />
        </Form.Item>

        <Form.Item label="文件要求" name="fileRequirements">
          <Input.TextArea
            v-model:value="formState.fileRequirements"
            placeholder="请输入文件要求"
            :rows="4"
          />
        </Form.Item>

        <Form.Item label="提交要求" name="submitRequirements">
          <Input.TextArea
            v-model:value="formState.submitRequirements"
            placeholder="请输入提交要求"
            :rows="4"
          />
        </Form.Item>
      </Form>
    </Modal>

  </div>
</template>

<style lang="less" scoped>
.task-page {
  .page-container {
    display: flex;
    gap: 16px;
    height: 100%;

    .tree-card {
      width: 280px;
      
      :deep(.ant-card-body) {
        padding: 0;
        height: calc(100% - 57px);
        overflow: auto;
      }
    }

    .content-card {
      flex: 1;
      overflow: hidden;
      display: flex;
      flex-direction: column;
    }
  }

  :deep(.ant-card-body) {
    padding: 24px;
  }

  .table-search {
    margin-bottom: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .search-left {
      // 左侧搜索区域样式
    }

    .search-right {
      // 右侧按钮区域样式
      margin-left: 16px;

      :deep(.ant-btn) {
        &[disabled] {
          cursor: not-allowed;
          
          .anticon + span {
            margin-left: 8px;
          }
        }
      }
    }
  }

  .submission-progress {
    display: flex;
    align-items: center;
    gap: 8px;

    .progress-detail {
      display: flex;
      flex-direction: column;
      
      .rate {
        font-size: 16px;
        font-weight: 500;
        color: rgba(0, 0, 0, 0.85);
      }
      
      .count {
        font-size: 12px;
        color: rgba(0, 0, 0, 0.45);
      }
    }
  }
}
</style> 